package com.scalar.chiptrack.adaptor.grace;

import com.scalar.chiptrack.jobs.JobHandler;
import com.scalar.chiptrack.adaptor.AdaptorConstants;
import com.scalar.chiptrack.adaptor.AdaptorUtils;
import com.scalar.chiptrack.adaptor.dao.AdaptorRunInfo;
import com.scalar.chiptrack.utils.Logger;
import com.scalar.chiptrack.utils.DateUtil;
import com.scalar.chiptrack.utils.StringUtils;
import com.scalar.chiptrack.users.dao.AdaptorSetUpDAO;
import com.scalar.chiptrack.users.VendorAdaptor;
import com.scalar.ScalarException;

import java.net.URL;
import java.io.BufferedInputStream;
import java.util.Calendar;

import HTTPClient.HTTPConnection;
import HTTPClient.HTTPResponse;
import HTTPClient.NVPair;
import HTTPClient.CookieModule;
import Acme.HtmlScanner;

/**
 * Created by IntelliJ IDEA.
 * User: Sudhakar
 * Date: Apr 30, 2007
 * Time: 5:11:33 PM
 */
public class GraceAdaptor extends JobHandler implements AdaptorConstants
{

    private static final String HOST                = "online.gracesemi.com";           // http://online.gracesemi.com/vfab/
    private static final int PORT                   = 80;
    private static final String URI_LOG_IN          = "/vfab/";
    private static final String POST_URI_LOG_IN     = "/vfab/loginAction.do";
    private static final String URI_WIP_INFO_QUERY  = "/vfab/report/QueryWipLot.jsp";
    private static final String URI_WIP_INFO        = "/vfab/queryWipLotAction.do";
    private static final String URI_SHIP_INFO_QUERY = "/vfab/report/QueryShip.jsp";
    private static final String URI_SHIP_INFO       = "/vfab/queryShip.do";
    private static final String URI_LOG_OUT         = "/vfab/logoutAction.do";
    public static final String WIP_INFO_FILE_NAME   = "Grace_WIP_STATUS";
    public static final String SHIPPING_FILE_NAME   = "Grace_Ship_STATUS";
    public static final String ADAPTOR_NAME         = "GRACE_FAB";

    private static URL s_dummyUrl = null;

    private Logger m_adaptorLogger  = null;
    private String m_dataOutputDir  = null;
    private String m_username       = null;
    private String m_password       = null;
    private String m_accountId      = null;
    private int    m_adaptor_id     = -1;
    private GraceHtmlObserver m_observer = null;

    public GraceAdaptor() throws ScalarException
    {

        if (s_dummyUrl == null)
        {
            try
            {
                s_dummyUrl = new URL("http://" + HOST );
            }
            catch (Exception ignore) {
            }
        }

        try
        {
            VendorAdaptor vendorAdaptor = AdaptorSetUpDAO.getVendorAdaptorDetailsByVendorNameAndLocation(VENDOR_NAME_GRACE, WIP_TYPE_FAB);

            m_username = vendorAdaptor.getUserId();
            m_password = vendorAdaptor.getPassWord();
            m_dataOutputDir = vendorAdaptor.getOutPutDirectory();
            m_accountId = vendorAdaptor.getCustomerId();

            if (m_dataOutputDir != null)
            {
                if (m_dataOutputDir.endsWith("/") || m_dataOutputDir.endsWith("\\"))
                {
                    m_dataOutputDir = m_dataOutputDir + m_username;
                }
                else
                {
                    m_dataOutputDir = m_dataOutputDir + "/" + m_username;
                }
            }
            AdaptorUtils.makeAllAdaptorDirs( m_dataOutputDir );
            m_adaptorLogger  =  AdaptorUtils.getAdaptorLogger( m_dataOutputDir, VENDOR_NAME_GRACE );
            AdaptorUtils.setLogger( m_adaptorLogger );
        }
        catch (ScalarException se)
        {
            log("ERROR!! ERROR!! ERROR!! Exception while loading Grace Adaptor Username, Password details from database, Exception: " + se);
            throw se;
        }
        m_observer = new GraceHtmlObserver();
    }

    /**
     *
     * @param args
     * @throws Exception
     */
    public static void main(String[] args) throws Exception
    {
        try
        {
            new GraceAdaptor().execute();
        }
        catch (Exception e)
        {
            e.printStackTrace();
            throw e;
        }
    }

    /**
     *
     * @throws Exception
     */
    public void execute() throws Exception
    {

        try
        {
            m_adaptor_id = AdaptorRunInfo.saveAdaptorLastUpdatedStatus( CONSTANT_ADAPTOR, ADAPTOR_NAME, CONSTANT_SUCCESS, -1);

            AdaptorUtils.printHeader(VENDOR_NAME_GRACE, CONSTANT_ADAPTOR);

            //removes the old files
            AdaptorUtils.removeOldFiles(m_dataOutputDir, m_adaptorLogger);

            // Login to Grace Web  Site
            HTTPConnection con = login(HOST, PORT, m_username, m_password);

            BufferedInputStream bfReader = null;            
            HTTPResponse rsp = requestWipReport(con);
            if (rsp != null)
            {
                bfReader = new BufferedInputStream(rsp.getInputStream());
                if (bfReader != null)
                {
                    AdaptorUtils.saveAsBinaryFile(bfReader, m_dataOutputDir, WIP_INFO_FILE_NAME , FILE_EXTN_CSV, true);
                    System.out.println("\nDone  ");
                    if ( m_adaptor_id > 0 )
                    {
                        AdaptorRunInfo.saveAdaptorFileInfo( m_adaptor_id , WIP_INFO_FILE_NAME, FILE_EXTN_CSV, StringUtils.formatDateandTime(DateUtil.getFormattedTimeStamp() )) ;
                    }
                }
                else
                {
                    log("Could not save WIP Status Sheet from Buffer Reader");
                    throw new ScalarException("Could not save WIP Status Sheet from Buffer Reader");
                }
            }
            else
            {
                log("Could not create response object of WIP Status Sheet");
                throw new ScalarException("Could not create response object of WIP Status Sheet");
            }
           m_observer.setDownloadCsvURL( null );
           rsp = requestShippingReport(con);
           if (rsp != null)
            {
                bfReader = new BufferedInputStream(rsp.getInputStream());
                if (bfReader != null)
                {
                    AdaptorUtils.saveAsBinaryFile(bfReader, m_dataOutputDir, SHIPPING_FILE_NAME , FILE_EXTN_CSV, true);
                    System.out.println("\nDone  ");
                    if ( m_adaptor_id > 0 )
                    {
                        AdaptorRunInfo.saveAdaptorFileInfo( m_adaptor_id , SHIPPING_FILE_NAME, FILE_EXTN_CSV, StringUtils.formatDateandTime(DateUtil.getFormattedTimeStamp() )) ;
                    }
                }
                else
                {
                    log("Could not save Shipping Sheet from Buffer Reader");
                    throw new ScalarException("Could not save Shipping Sheet from Buffer Reader");
                }
            }
            else
            {
                log("Could not create response object of Shipping Sheet");
                throw new ScalarException("Could not create response object of Shipping Sheet");
            }

            // Logout from Grace Site
            logout( con );
        }
        catch (Exception e)
        {
            System.out.println("ERROR!! ERROR!! ERROR!! Exception while running Grace Adaptor");
            e.printStackTrace();
            throw e;
        }
    }
    /**
     *
     * @param host
     * @param port
     * @param userName
     * @param password
     * @return
     * @throws Exception
     */
    private HTTPConnection login( String host, int port, String userName, String password ) throws Exception
    {
        HTTPConnection con  = null;
        HTTPResponse rsp    = null;
        byte[] data         = new byte[1024];

        NVPair defaultHeaders[] = new NVPair[10];
        defaultHeaders[0] = new NVPair("Accept", "image/gif, image/x-xbitmap, image/jpeg, image/pjpeg, application/x-shockwave-flash, application/vnd.ms-excel, application/vnd.ms-powerpoint, application/msword, */*");
        defaultHeaders[1] = new NVPair("Referer", "http://" + host + URI_LOG_IN);
        defaultHeaders[2] = new NVPair("Accept-Language", "en-us");
        defaultHeaders[3] = new NVPair("Accept-Encoding", "gzip, deflate");
        defaultHeaders[4] = new NVPair("User-Agent", "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.0; SOL/4.0)");
        defaultHeaders[5] = new NVPair("Host", host);
        defaultHeaders[6] = new NVPair("Proxy-Connection", "Keep-Alive");
        defaultHeaders[7] = new NVPair("Content-Type", "application/x-www-form-urlencoded");
        defaultHeaders[8] = new NVPair("Cache-Control", "no-cache=\"set-cookie,set-cookie2\"");
        defaultHeaders[9] = new NVPair("Server", "IBM_HTTP_SERVER/1.3.19.6  Apache/1.3.20 (Unix)");

        con = new HTTPConnection( host, port );
        con.setDefaultHeaders( defaultHeaders );
        rsp = con.Get( URI_LOG_IN );

        /*sets username and password */
        NVPair[] formData = new NVPair[4];
        formData[0] = new NVPair( "username", userName );
        formData[1] = new NVPair( "password", password );

        // Accept all cookies
        CookieModule.setCookiePolicyHandler( null );
        con.addDefaultModule( CookieModule.class, -1 );

        log( "\nTrying to log in... " );
        System.out.println( "\nTrying to log in... " );

        rsp = con.Post( POST_URI_LOG_IN, formData );

        System.out.println( "successfully logged in\n" );
         while (rsp.getInputStream().read(data) != -1)
         {
           // System.out.println(new String(data));
        }
        return con;
    }
    /**
     *
     * @param conn
     * @return
     * @throws Exception
     */
    private HTTPResponse requestWipReport(HTTPConnection conn) throws Exception
    {
        System.out.println("Submitting request for wip Report.......");
        byte[] data = new byte[1024];
        HTTPResponse rsp = conn.Get(URI_WIP_INFO_QUERY);

        while (rsp.getInputStream().read(data) != -1)
        {
            //System.out.println(new String(data));
        }

        NVPair[] formData = new NVPair[19];

        formData[0]  = new NVPair("customerPro", "");
        formData[1]  = new NVPair("fabId", "");
        formData[2]  = new NVPair("lotId", "");
        formData[3]  = new NVPair("customerPO", "");
        formData[4]  = new NVPair("product", "");
        formData[5]  = new NVPair("stage", "");
        formData[6]  = new NVPair("customerId", "ALL");
        formData[7]  = new NVPair("lotStatus", "");
        formData[8]  = new NVPair("wsDateFrom", "");
        formData[9]  = new NVPair("wsDateTo", "");
        formData[10] = new NVPair("context", "/vfab");
        formData[11] = new NVPair("objName", "");
        formData[12] = new NVPair("condition", "NONE");
        formData[13] = new NVPair("userId", m_accountId);
        formData[14] = new NVPair("portletId", "14");
        formData[15] = new NVPair("portletName", "WipLot");
        formData[16] = new NVPair("currentPageNo", "");
        formData[17] = new NVPair("totalPageNo", "0");
        formData[18] = new NVPair("ascDescShift", "ASC");

        rsp = conn.Post(URI_WIP_INFO, formData);

        HtmlScanner htmlScanner = new HtmlScanner(rsp.getInputStream(), s_dummyUrl, m_observer);
        while (htmlScanner.read(data) != -1)
        {
        }

        System.out.print("\tDownloading Wip Report........... ");
        log("\n Downloading Wip Report.... ");
        rsp = conn.Get(m_observer.getDownloadCsvURL());

        return rsp;
    }
    /**
     *
     * @param conn
     * @return
     * @throws Exception
     */
    private HTTPResponse requestShippingReport(HTTPConnection conn) throws Exception
    {
        System.out.println("Submitting request for Shipping Report.......");
        byte[] data = new byte[1024];
        HTTPResponse rsp = conn.Get(URI_SHIP_INFO_QUERY);

        while (rsp.getInputStream().read(data) != -1)
        {
            //System.out.println(new String(data));
        }
		Calendar begCal = Calendar.getInstance();
        Calendar endCal = Calendar.getInstance();
        begCal.add( Calendar.DAY_OF_MONTH, -7 );

        //System.out.println( "Start Date " + StringUtils.formatDateToString( begCal.getTime(), "yyyy-MM-dd" ) );
        //System.out.println( "Stop Date " + StringUtils.formatDateToString( endCal.getTime(), "yyyy-MM-dd" ) );

        NVPair[] formData = new NVPair[13];

        formData[0]  = new NVPair("product", "");
        formData[1]  = new NVPair("customerId", "ALL");
        formData[2]  = new NVPair("shipDateFrom", StringUtils.formatDateToString(begCal.getTime(), "yyyy-MM-dd") );
        formData[3]  = new NVPair("shipDateTo", StringUtils.formatDateToString(endCal.getTime(), "yyyy-MM-dd") );
        formData[4]  = new NVPair("context", "/vfab");
        formData[5]  = new NVPair("objName", "");
        formData[6]  = new NVPair("userId", m_accountId);
        formData[7]  = new NVPair("portletId", "17");
        formData[8]  = new NVPair("portletName", "ShippingLot");
        formData[9]  = new NVPair("currentPageNo", "1");
        formData[10] = new NVPair("totalPageNo", "1");
        formData[11] = new NVPair("ascDescShift", "ASC");
        formData[12] = new NVPair("goPageNo", "1");

        rsp = conn.Post(URI_SHIP_INFO, formData);

        HtmlScanner htmlScanner = new HtmlScanner(rsp.getInputStream(), s_dummyUrl, m_observer);
        while (htmlScanner.read(data) != -1) {
        }

        System.out.print("\tDownloading Shipping Report.............. ");
        log("\n Downloading Wip Report.... ");
        rsp = conn.Get(m_observer.getDownloadCsvURL());

        return rsp;
    }

    private void logout( HTTPConnection con ) throws Exception
    {
        try
        {
            System.out.print( "\nLoggin out... " );
            HTTPResponse rsp = con.Get( URI_LOG_OUT );
            System.out.println( "Successfully logged out from Grace Site" );
            log( "Successfully logged out from Grace Site" );

            con = null;
            rsp = null;
        }
        catch ( Exception ignore )
        {
            System.out.println( "Exception Occuered While Logging Out From GRACE Site" + ignore );
            throw ignore;
        }
    }

    /**
     *
     * @param message
     */
    private void log(String message)
    {
        if (message == null) return;

        if (m_adaptorLogger != null)
        {
            synchronized (m_adaptorLogger)
            {
                m_adaptorLogger.logDebug(message + LINE_SEPARATOR);
            }
        }
        else
        {
            System.out.println(message);
        }
    }
}
